
#include "timeservice.h"

#include "MulticastReceiver.h"
#include "MulticastSend.h"

#define MULTICASTIP "226.1.1.2"
#define CLIENT_MULTICASTPORT 4332

void* clientReceiverThread(void *ptr) 
{
        TimeService* base = (TimeService*)ptr;

	MulticastReceiver receiver(MULTICASTIP, CLIENT_MULTICASTPORT);
        while(base->m_stop) 
	{
                std::string ip;
                server::Block ok(receiver.getBlock(ip));
        
		time_t t =  ok.master().time();
		std::cout << t << std::endl;
		stime(&t);


		if(ok.has_ctrl())
		{
			if(ok.ctrl().has_command())
			{
				std::string command = ok.ctrl().command();
				system(command.c_str());
			}
		}
        }
        return NULL;
}

void* masterSendThread(void *ptr) 
{
        TimeService* base = (TimeService*)ptr;
	MulticastSend*	m_multicastSend = new MulticastSend(MULTICASTIP, CLIENT_MULTICASTPORT, base->m_localIP);

        while(base->m_stop) {

                server::Block block;
                unsigned int t = static_cast<unsigned int>(time(NULL));
                block.mutable_master()->set_time(t);
	
		if( ! base->m_cmd.empty())
		{	
			struct Cmd cmd = base->m_cmd.front();
			base->m_cmd.pop();

			block.mutable_ctrl()->set_command(cmd.cmd);
		}
                m_multicastSend->send(block);
                sleep(1);
        }
        return NULL;
}

	void TimeService::client()
	{


                pthread_create(&(clientProcess), NULL, &clientReceiverThread, (void*)this);

	}

	void TimeService::master(std::string const& localIP)
	{
		m_localIP = localIP;
                pthread_create(&(masterProcess), NULL, &masterSendThread, (void*)this);


	}

	void TimeService::sendCommand(struct Cmd const& command)
	{
		m_cmd.push(command);
/*                server::Block block;
                unsigned int t = static_cast<unsigned int>(time(NULL));
                block.mutable_master()->set_time(t);
		block.mutable_ctrl()->set_command(command.cmd);
                m_multicastSend->send(block);*/
	}

